<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\meituan\controller;

use app\meituan\model\MeituanOrderModel;
use app\meituan\service\MeituanOrderImportService;
use cmf\controller\RestBaseController;
use think\facade\Db;

/**
 * Class IndexController
 * @package api\demo\controller
 */
class IndexController extends RestBaseController
{
    public function index()
    {
        $data = $this->request->param();
        $this->success('请求成功!', ['test' => 'test', 'data' => $data]);
    }


    /**
     * 获取美团链接
     * User: sunc
     * Date: 2021/7/7 16:37
     */
    public function getMeituanUrl()
    {
        $param = $this->request->param();
        $postService = new MeituanOrderImportService();
        $data = $postService->createUrl($param);
        if (is_error($data)) {
            $this->success('请求成功!', ['data' => $data]);
        }
    }


    /**
     * 解析短连接
     * User: sunc
     * Date: 2021/7/7 16:08
     */
    public function sortUrl()
    {
        $code = $this->request->get('code');
        $info = Db::name('long_short_url')->where(['short_url_code' => $code])->field('long_url')->find();
        if (!empty($info)) {
            header('Location:' . $info['long_url']);
        }
    }

    /**
     * 订单回调
     * User: sunc
     * Date: 2021/7/7 16:55
     */
    public function notify()
    {
        $data = file_get_contents('php://input');
        file_put_contents(__DIR__ . '/a.json', $data, 8);
        $data = json_decode($data, true);
        if (empty($data)){
            return json_encode(['errcode' => 1, 'errmsg' => 'ok']);
        }
        $order = new MeituanOrderModel;
        $order = $order->where('orderid', $data['orderid'])->find();
        if (empty($order)) {
            $order = new MeituanOrderModel;
        }
        $saveData = [
            'orderid' => $data['orderid'],
            'smstitle' => $data['smstitle'],
            'paytime' => $data['paytime'],
            'type' => $data['type'],
            'sid' => $data['sid'],
            'uid' => $data['uid'],
            'status' => $data['status'],
            'total' => $data['total'],
            'payprice' => $data['direct'],
            'ratio' => $data['ratio'],
            'tradeTypeList' => json_encode($data['tradeTypeList']),
        ];
        $res = $order->save($saveData);
        if ($res) {
            return json_encode(['errcode' => 0, 'errmsg' => 'ok']);
        } else {
            return json_encode(['errcode' => 1, 'errmsg' => 'ok']);
        }
    }

}
